package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @description: 用户注册，讲数据插入表中
 * @author: enhui
 **/
@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    JavaMailSender mailSender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        UserRegisterResponse response = new UserRegisterResponse();
        try {//参数校验，判空的校验
            request.requestCheck();
            //用户名不能重复，验证用户名是否重复
            validUserName(request);

            //验证通过，向用户表中插入数据
            Member member = new Member();
            member.setEmail(request.getEmail());
            member.setUsername(request.getUserName());
            //Password加密处理
            String password = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
            member.setPassword(password);
            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setIsVerified("N");
            member.setState(1);
            int memberCount = memberMapper.insert(member);
            if (memberCount != 1) {
                //插入失败
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }

            //向用户验证表中插入数据
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(member.getUsername());
            //设置uuid，这里使用与username和password有关的值
            String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
            //加密
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsVerify("N");
            userVerify.setIsExpire("N");
            int userVerifyCount = userVerifyMapper.insert(userVerify);
            if (userVerifyCount != 1) {
                //插入失败
                response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
                return response;
            }

            //发送用户邮件，邮件激活是一个链接，有一个接口去处理我们的用户激活
            //就是发送verfiy的这个链接http://localhost:8080/user/verify?uid=xxx&username=xxx
            //使用uuid和username
            sendEmail(uuid, request);

            //打印成功日志
            log.info("注册成功，注册参数request:{}", JSON.toJSONString(request));

            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            response.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    /**
     * 发送邮件
     *
     * @param uuid
     * @param request 请求
     */
    private void sendEmail(String uuid, UserRegisterRequest request) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("CSMALL用户激活");
        message.setFrom("enhui312@163.com");
        message.setTo(request.getEmail());
        StringBuffer buffer = new StringBuffer();
        buffer.append("http://localhost:8080/user/verify?uid=").
                append(uuid).append("&username=").append(request.getUserName());
        message.setText(buffer.toString());
        mailSender.send(message);
    }


    /**
     * 查表验证用户名不能重复
     *
     * @param request
     */
    private void validUserName(UserRegisterRequest request) {
        //先查表
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        //判空，如果为空，说明不重复
        if (!CollectionUtils.isEmpty(members)) {
            //为空，抛出异常
            new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(), SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
